﻿using System.Linq;
using System.Web.Mvc;
using ML.Entity;
using ML.IBusiness;

namespace ML.WebApi.Controllers
{
    public class InvitationProfitController : BaseApiController
    {
        private readonly IInvitationProfitBusiness invitationProfitBusiness;
        private readonly IOrderBusiness ordreBusiness;
        private readonly IUserInvitationBusiness userInvitationBusiness;

        public InvitationProfitController(IInvitationProfitBusiness _invitationProfitBusiness, IOrderBusiness _ordreBusiness, IUserInvitationBusiness _userInvitationBusiness)
        {
            this.invitationProfitBusiness = _invitationProfitBusiness;
            this.ordreBusiness = _ordreBusiness;
            this.userInvitationBusiness = _userInvitationBusiness;
        }

        /// <summary>
        /// 根据用户id,获取该用户的邀请计数信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/invitationprofit/userid")]
        public BaseResult<InvitationProfitEntity> Get(string userId)
        {
            var successCount = 0;
            var userInvitation = userInvitationBusiness.GetUserInvitationByUserId(userId);//根据邀请人id，获取所有被邀请人信息
            foreach (var item in userInvitation.data)//遍历被邀请人信息
            {
                var orderlist = ordreBusiness.GetListByUserId(item.UserId).data;//根据被邀请人id，获取被邀请人的订单
                if (orderlist != null)
                {
                    //查询，所有被邀请人成功下单的数量是否>=1
                    var result = orderlist.Count(o => o.PayState == (int)PayStateStatus.havepaid && o.State == (int)OrderStatus.finish) >= 1;
                    if (result)
                    {
                        successCount++;
                    }
                }
            }
            invitationProfitBusiness.UpdataSuccessCountCountByUserId(successCount, userId);//如果被邀请人已经成功完成一单，则计数一次
            var returnData = invitationProfitBusiness.GetByUserId(userId).data;
            if (returnData != null)
            {
                return new BaseResult<InvitationProfitEntity>(returnData);
            }
            return new BaseResult<InvitationProfitEntity>(new InvitationProfitEntity { InvitationCount = 0, UserId = userId, SuccessCount = 0 });
        }
    }
}